#ifndef TUNNEL_H
#define TUNNEL_H

#include "my_ipc.h"
#include <sys/types.h>
#include <time.h>
#include <string.h>

#define tunnel_key 0x199705
#define mail_key_shm 0x198706
#define mail_key_sem 0x200706
#define mail_read 0x180706
#define mail_write 0x180705
#define light_sem_key 0x189707
#define tun_shm_key 0x189708
#define tun_dir_key 0x189709
#define light_shm_key 0x180709

typedef struct {
    int max_car_in; // 隧道最大容量
    int* car_in; //隧道现有车辆数（共享内存）
    int* current_direction; // 当前车流方向 (0=东向西, 1=西向东)
    int tun_shmid;
    int tun_car_semid; // 控制车辆进入的信号量
    int tun_dir_semid; // 用于控制方向的信号量
    
    int mail_sum;
    int mail_size;
    int travel_time;
    int *mail_shmid;
    int *mail_semid;
    int readcount;
    int writecount;

    int *traffic_light;       // 当前红绿灯状态：0=东向西绿灯，1=西向东绿灯
    int light_switch_time;   // 方向切换时间阈值（秒）
    time_t last_switch_time; // 上次切换时间
    int *waiting_counts;     // 各方向等待车辆数（共享内存）
    int light_shmid;         // 红绿灯状态共享内存ID
    int light_semid;         // 红绿灯信号量ID
} Tunnel;

// 函数声明
key_t generate_mail_key(int mailbox_index);

void creat_tunnel_sem(Tunnel *t);
void creat_mail_shared(Tunnel *t);
void creat_mail_sem(Tunnel *t);
void print_memory(Tunnel *t);
void del_tunnel_sem(Tunnel *t);
void del_mail_shared(Tunnel *t);
void del_mail_sem(Tunnel *t);
Tunnel* create_tunnel(int max_car, int mail_sum, int mail_size, int travel_time);

void init_traffic_light(Tunnel *t);
void update_traffic_light(Tunnel *t);
void traffic_light_controller(Tunnel *t);
void update_light_switch_time(Tunnel *t);

#endif // TUNNEL_H
